#include "daemon_process.h"
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/reboot.h>
#include <sys/signal.h>
#include "../thirdparty/log/log.h"

/**
 * @brief 初始化进程
 * @param name 进程名称
 * @return SubProcess_t* 进程结构体指针
 */
SubProcess_t *daemon_process_init(const char *name)
{
    SubProcess_t *process = (SubProcess_t *)malloc(sizeof(SubProcess_t));
    if (process == NULL)
    {
        return NULL;
    }
    process->param = name;
    process->pid = -1;
    process->fail_count = 0; // 初始化失败次数为0
    return process;
}

/**
 * @brief 检查进程是否在运行，如果不在运行则启动进程
 * @param process 进程结构体指针
 * @return int 0:成功, 1:失败
 */
int daemon_process_checkExece(SubProcess_t *process)
{
    int status;
    // 如果进程已经启动，则检查进程是否还在运行
    if (process->pid > 0 && waitpid(process->pid, &status, WNOHANG) == 0)
    {
        return 0; // 进程还在运行
    }
    if (status != 0)
    {
        process->fail_count++; // 进程失败次数加1
        if (process->fail_count > MAX_PROCESS_FAIL)
        {
            log_error("子进程失败次数过多，重启系统");
            reboot(RB_AUTOBOOT);
        }
    }

    // 如果进程未启动，则启动子进程
    process->pid = fork();
    // 子进程
    if (process->pid == 0)
    {
        char *args = {EXE_PATH, process->param, NULL};
        execve(process->param, args, NULL);
        log_error("execve %s failed", process->param);
        // execve失败，则退出子进程
        _exit(EXIT_FAILURE);
    }
    return 0;
}

void daemon_process_destroy(SubProcess_t *process)
{
    // 关闭子进程
    kill(process->pid, SIGTERM);
    // 等待子进程结束
    waitpid(process->pid, NULL, 0);
    // 释放进程结构体
    free(process);
}